/******************************************************************************
 * @File name   :      DealerUsrGrpApprovalDaoImpl.java
 *
 * @Author      :      chen shixiang
 *
 * @Date        :      2011-6-3
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-6-3 上午10:16:04        chen shixiang     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.framework.dm.approval.dao.impl;

import java.util.List;

import javax.inject.Inject;

import com.cap.bts.framework.dm.approval.dao.IDealerUsrGrpApprovalDao;
import com.cap.bts.framework.dm.approval.domain.UserGroupApplication;
import com.cap.bts.framework.dm.approval.dto.QueryApplicationDto;
import com.cap.bts.framework.dm.approval.dto.QueryApproveDto;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.cap.bts.framework.approvalrule.constants.ApplicationTypeConstants;
import com.cap.bts.framework.common.dao.impl.BaseDaoImpl;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.usermgnt.constant.OrganizationType;


/**
 * dealer user group approval dao implment class
 */
@Repository("dealerUsrGrpApprovalDao")
public class DealerUsrGrpApprovalDaoImpl extends BaseDaoImpl<UserGroupApplication, Long> implements
    IDealerUsrGrpApprovalDao {

    /**
     * @Date : 2011-6-3
     * @param clazz
     *            UsrgrpApplication
     */
    @Inject
    public DealerUsrGrpApprovalDaoImpl(
			@Value("com.cap.bts.framework.dm.approval.domain.UserGroupApplication") Class<UserGroupApplication> clazz) {
        super(clazz);
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2011-6-3
     * @see com.cap.bts.gdms.dm.approval.dao.IDealerUsrGrpApprovalDao#getUsrGrpApprovalByDto(com.cap.bts.gdms.dm.approval.dto.QueryApplicationDto)
     **/
    @Override
    public List<UserGroupApplication> getUsrGrpApprovalByDto(QueryApplicationDto dto, boolean isPaging) {
 
        String [] ruleSteps = dto.getRuleStep().split(",");
        StringBuilder ruleStepIn = new StringBuilder();
        ruleStepIn.append("('").append(StringUtils.join(ruleSteps, "','")).append("')");
        String countHql = "select count(*)";
        String hql=" from UserGroupApplication ua where ua.brandId="+dto.getBrandId()
        +" and exists(select rs.id from ApplicationRuleStep rs where rs.applicationId=ua.id " +
                "and rs.applicationType="+ApplicationTypeConstants.USERGROUP_APPLICATION_TYPE
                +" and rs.ruleStep in "+ruleStepIn.toString()+" )";
        
       if (Utils.notEmpty(dto.getDealerCode())){
           String[] dealerArray = dto.getDealerCode().split(",");
           String dealerStr = "'" + StringUtils.join(dealerArray, "','") + "'";
           hql +=" and exists (select 1 from Organization org where org.id=ua.dealerOrgId and org.orgCode in(" + dealerStr + "))";            
       }
       //页面传过来mac条件，登录人当前岗位所在组织是的orgType是mac做权限控制
       if(Utils.notNullAndZeroAndNegativeOne(dto.getMacCode())){
           hql += " and exists(select 1 from OrgDealer sd join sd.sgmOrg macorg where macorg.orgType=" + OrganizationType.MAC + " and macorg.orgCode='" + dto.getMacCode() + "' and sd.dealerOrg.id=ua.dealerOrgId )";
       }
      //页面传过来RFS条件，登录人当前岗位所在组织是的orgType是RFs做权限控制(不包括别克的市场副总)
       if (Utils.notNullAndZeroAndNegativeOne(dto.getRfsCode())){
           hql += " and exists(select 1 from OrgDealer sd join sd.sgmOrg macorg where macorg.orgType=" + OrganizationType.MAC + " and macorg.parentOrgCode='" + dto.getRfsCode() + "' and sd.dealerOrg.id=ua.dealerOrgId)";
       }
       //页面传过来的条件是Rpc
       if (Utils.notNullAndZeroAndNegativeOne(dto.getRpcCode())){
           
           hql += " and exists(select 1 from OrgDealer sd join sd.sgmOrg rpcorg where rpcorg.orgType=" + OrganizationType.RPC + " and rpcorg.orgCode='" + dto.getRpcCode() + "' and sd.dealerOrg.id=ua.dealerOrgId)";
       }
        if (Utils.notEmpty(dto.getUserName())) {// seach userName
            hql += " and ua.employeeInfo.employeeName like '" + dto.getUserName() + "%'";
        }
        if (Utils.notEmpty(dto.getMobilePhone())) {// seach mobilePhone
            hql += " and ua.employeeInfo.mobilePhone='" + dto.getMobilePhone() + "'";
        }
        if(dto.getSearchUserGroupId()!=0){
            hql+=" and ua.usrgrpCode in (select ug.userGroupCode from UserGroup ug where ug.id="+dto.getSearchUserGroupId()+" )"; //关联用户绿
        }
        countHql = countHql + hql;
        hql+=" order by ua.orgCode";
        if (isPaging) {
            return getListByQueryWithPaging(hql, countHql, dto.getPager());// getListByQuery(hql);//
        } else {
            return getListByQuery(hql);// getListByQuery(hql);//
        }
    }
    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2011-6-3
     * @see com.cap.bts.gdms.dm.approval.dao.IDealerUsrGrpApprovalDao#getUsrGrpApprovalByDto(com.cap.bts.gdms.dm.approval.dto.QueryApplicationDto)
     **/
    @Override
    public int getUsrGrpApprovalReminderByDto(QueryApplicationDto dto) {
        //取 rfs dealer
        String rfsHql = " and exists( select sd.dealerOrg from OrgDealer sd,Organization org "
            + "where sd.sgmOrg.id=org.id and org.orgType=" + OrganizationType.MAC
            + "and exists(select org2.id from Organization org2 where org2.parentOrgCode='"
            + dto.getRfsCode() + "' and sd.sgmOrg=org2.id ) and ua.dealerOrgId=sd.dealerOrg)";
      //取 rpc 关联 dealer
        String rpcHql = " and exists( select sd.dealerOrg from OrgDealer sd,Organization org "
            + "where sd.sgmOrg.id=org.id and org.orgType=" + OrganizationType.RPC
            + "and org.orgCode='" + dto.getRpcCode() + "' and ua.dealerOrgId=sd.dealerOrg.id)";
      //取 mac 关联 dealer
        String macHql = " and exists( select sd.dealerOrg from OrgDealer sd,Organization org "
            + "where sd.sgmOrg.id=org.id and org.orgType=" + OrganizationType.MAC
            + "and org.orgCode='" + dto.getMacCode() + "' and ua.dealerOrgId=sd.dealerOrg.id)";

        String countHql = "select count(*)";

        String hql=" from UserGroupApplication ua where ua.brandId="+dto.getBrandId()
            +" and exists(select rs.id from ApplicationRuleStep rs where rs.applicationId=ua.id and rs.applicationType="
            +ApplicationTypeConstants.USERGROUP_APPLICATION_TYPE+" and rs.ruleStep='"+dto.getRuleStep()+"' )"; //关联审批结点

        if(Utils.notNullAndZero(dto.getApprovalCategory())){
            hql+=" and ua.approvalCategory="+dto.getApprovalCategory()+"";
        }
        if (dto.getRfsCode() != null && !"".equals(dto.getRfsCode())) {
            hql += rfsHql;
        }
        if (dto.getRpcCode() != null && !"".equals(dto.getRpcCode())) {
            hql += rpcHql;
        }
        if (dto.getMacCode() != null && !"".equals(dto.getMacCode())) {
            hql += macHql;
        }
        int count = this.countByQuery(countHql+hql);
        return count; 
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2011-7-1
     * @see com.cap.bts.gdms.dm.approval.dao.IDealerUsrGrpApprovalDao#getUserGroupApplicationByEmployeeId(long)
    **/
    @Override
    public UserGroupApplication getUserGroupApplicationByEmployeeId(long employeeId) {
        String hql = "from UserGroupApplication a where a.employeeInfo.id=" + employeeId;
        
        List <UserGroupApplication> userGroupApplicationList = this.getListByQuery(hql);
        if (userGroupApplicationList != null && userGroupApplicationList.size() > 0){
            
            return userGroupApplicationList.get(0);
            
        }
        return null;
        
    }

    @Override
    public List<UserGroupApplication> getApproveResultByPageCondiation(QueryApproveDto dto , boolean isPaging){
    	 
		String hql = " from UserGroupApplication ua where 1=1 ";
		String countHql = "select count(*)";
		if(dto.getBrandId()!=null && dto.getBrandId().longValue()>0){
			hql+=" and ua.brandId="+dto.getBrandId();
		}
		if (Utils.notEmpty(dto.getDealerCode())) {
			String[] dealerArray = dto.getDealerCode().split(",");
			String dealerStr = "'" + StringUtils.join(dealerArray, "','") + "'";
			hql += " and exists (select 1 from Organization org where org.id=ua.dealerOrgId and org.orgCode in("
					+ dealerStr + "))";
		}
		// 大区
		if (Utils.notEmpty(dto.getRfsCode())) {
			hql += " and exists(select 1 from OrgDealer sd join sd.sgmOrg macorg where macorg.orgType="
					+ OrganizationType.MAC
					+ " and macorg.parentOrgCode='"
					+ dto.getRfsCode()
					+ "' and sd.dealerOrg.id=ua.dealerOrgId)";
		}
		if (Utils.notEmpty(dto.getUserName())) {// seach userName
			hql += " and ua.employeeInfo.employeeName like '"
					+ dto.getUserName() + "%'";
		}
		if (Utils.notEmpty(dto.getMobilePhone())) {// seach mobilePhone
			hql += " and ua.employeeInfo.mobilePhone='" + dto.getMobilePhone()
					+ "'";
		}
		//状态
		if(Utils.notNullAndZeroAndNegativeOne(dto.getStatus())){
			hql += " and exists (select 1 from ApplicationApproval happ where happ.applicationId=ua.id and happ.approverResult="
				+ dto.getStatus() +"and happ.approverUserId="+dto.getUser().getId()+")";
		}else{
			hql += " and exists (select 1 from ApplicationApproval happ where happ.applicationId=ua.id and happ.approverUserId="+dto.getUser().getId()+")";
		}
		//申请时间
		if(Utils.notEmpty(dto.getFromApproveDate())){
            hql+=" and ua.createDate>=to_date('"+dto.getFromApproveDate()+"','yyyy-mm-dd')";
        }
        if(Utils.notEmpty(dto.getToApproveDate())){
            hql+=" and ua.createDate<=to_date('"+dto.getToApproveDate()+" 23:59:59','yyyy-MM-dd hh24:Mi:ss')";
        }
		countHql = countHql + hql;
		hql += " order by ua.orgCode";
		if (isPaging) {
			return getListByQueryWithPaging(hql, countHql, dto.getPager());
		} else {
			return getListByQuery(hql);
		}
    }
    
    public List<UserGroupApplication> getApproveResultByEmployeeCode(String employeeCode){
    	String hql = " from UserGroupApplication ua where 1=1 ";
		if (Utils.notEmpty(employeeCode)) {
			hql+=" and ua.employeeInfo.employeeCode='"+employeeCode+"'";
		}
		hql += " order by ua.id desc";
		return getListByQuery(hql);
    }
}
